/**
 *添加 运费模板
 */
import React, {Component} from 'react';
import 'antd/dist/antd.css';
import {requestUrl, goods, china, template} from '../../value';
import app from '../../app';
import {
    Button,
    Form,
    Input,
    Icon,
    Row,
    Table,
    Col,
    Select,
    message,
    InputNumber,
    Checkbox,
    Modal,
    Radio,
    Tree
} from 'antd';
import moment from 'moment';
import {config} from '../../config';
import data from '../JSON/city.json';

const path = config.path;
const FormItem = Form.Item;
const Option = Select.Option;
const confirm = Modal.confirm;
const TreeNode = Tree.TreeNode;
const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;
const pageLength = 7;

class AddTransport extends Component {
    constructor(props) {
        super(props);
        this.state = {
            saveLoading: false,
            provinces: [],
            citys: [],
            countys: [],
            cityData: [],
            currentPost: '1',  //显示下一步或者保存并返回的按钮
            firstPage: 'block',  //卖家承担运费的第一页是否显示
            selectDeliverVisible: 'none', //是否显示第二页的运送方式（值为快递 平邮还是ＥＭＳ）

            count: 0, //供传给服务器时，给相同运费的地区设置一个标志，方便查询
            mySelftPost: false,  //点击第一页的保存之后就不能选择自定义运费
            loadingTwo: false, //第二个页面的保存加载按钮
        };
    }


    formItemLayout = {
        labelCol: {span: 4},
        wrapperCol: {span: 8},
    };
    formTimeItemLayout = {
        labelCol: {span: 4},
        wrapperCol: {span: 17},
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        return (
            <span>
                <Row>
                    <Row className='titleSize btnBottom'>新增运费模板</Row>
                    <Row style={{display: 'flex', marginBottom: '20px'}}>
                        <Col span={24}>
                            <Form className="login-form" style={{display: this.state.firstPage}}>
                                <Col>
                                    <FormItem label={"模板名称:"} {...this.formItemLayout}>
                                        {getFieldDecorator('template_name', {
                                            rules: [{required: true, message: '请输入模板名称!'}],
                                        })(
                                            <Input placeholder="请输入"/>
                                        )}
                                    </FormItem>
                                </Col>
                                {/*<Col span={8}>*/}
                                {/*<FormItem label={"宝贝地址"} {...this.formDistrictItemLayout}>*/}
                                {/*{getFieldDecorator('province', {*/}
                                {/*rules: [{required: true, message: '请选择宝贝地址!'}],*/}
                                {/*})(*/}
                                {/*<Select style={{width: 140}} placeholder="省" onChange={(value) => {*/}
                                {/*this.handleSelectProvince(value)*/}
                                {/*}}>*/}
                                {/*{*/}
                                {/*this.state.provinces.map((provinceItem, provinceIndex) => {*/}
                                {/*return (*/}
                                {/*<Option key={provinceIndex}*/}
                                {/*value={provinceItem.id + ''}>{provinceItem.name}</Option>*/}
                                {/*)*/}
                                {/*})*/}
                                {/*}*/}
                                {/*</Select>*/}
                                {/*) }*/}
                                {/*</FormItem>*/}
                                {/*</Col>*/}
                                {/*<Col span={4}>*/}
                                {/*<FormItem label={""} {...this.formDistrictItemLayout}>*/}
                                {/*{getFieldDecorator('city')(*/}
                                {/*<Select style={{width: 140}} placeholder="市" onChange={(value) => {*/}
                                {/*this.handleSelectCity(value)*/}
                                {/*}}>*/}
                                {/*{*/}
                                {/*this.state.citys.map((cityItem, cityIndex) => {*/}
                                {/*return (*/}
                                {/*<Option key={cityIndex}*/}
                                {/*value={cityItem.id + ''}>{cityItem.name}</Option>*/}
                                {/*)*/}
                                {/*})*/}
                                {/*}*/}
                                {/*</Select>*/}
                                {/*)}*/}
                                {/*</FormItem>*/}
                                {/*</Col>*/}
                                {/*<Col span={8}>*/}
                                {/*<FormItem label={""} {...this.formDistrictItemLayout}>*/}
                                {/*{getFieldDecorator('county')(*/}
                                {/*<Select style={{width: 140}} placeholder="区">*/}
                                {/*{*/}
                                {/*this.state.countys.map((countyItem, countyIndex) => {*/}
                                {/*return (*/}
                                {/*<Option key={countyIndex}*/}
                                {/*value={countyItem.id + ''}>{countyItem.name}</Option>*/}
                                {/*)*/}
                                {/*})*/}
                                {/*}*/}
                                {/*</Select>*/}
                                {/*) }*/}
                                {/*</FormItem>*/}
                                {/*</Col>*/}
                                <Col span={24}>
                                    <FormItem label={"发货时间:"} {...this.formTimeItemLayout}>
                                        {getFieldDecorator('template_time', {
                                            rules: [{required: true, message: '请选择发货时间!'}],
                                        })(
                                            <Select style={{width: '200px'}}>
                                                <Option value="12">12小时</Option>
                                                <Option value="24">24小时</Option>
                                                <Option value="48">48小时</Option>
                                            </Select>
                                        )}
                                    </FormItem>
                                    <FormItem label={"注意"} {...this.formTimeItemLayout}>
                                        {getFieldDecorator('zhuyi')(
                                            <span>如实设定宝贝的发货时间，不仅可避免发货咨询和纠纷，还能促进成交</span>
                                        )}
                                    </FormItem>

                                    <FormItem label={"是否包邮:"} {...this.formItemLayout}>
                                        {getFieldDecorator('template_shipping', {
                                            rules: [{required: true, message: '请选择是否包邮!'}],
                                        })(
                                            <RadioGroup onChange={(e) => this.handleIsPost(e)}
                                                        style={{paddingTop: '0'}}>
                                                <Radio disabled={this.state.mySelftPost} value={'0'}>自定义运费</Radio>
                                                <Radio value={'1'}>卖家承担运费</Radio>
                                            </RadioGroup>
                                        )}
                                    </FormItem>
                                </Col>

                                <Col span={24} style={{display: this.state.currentPost == '1' ? 'none' : 'block'}}>
                                    <FormItem label={"运送方式说明:"} {...this.formItemLayout}>
                                        {(
                                            <span style={{color: '#9fa4a8'}}>除指定地区外，其余地区的运费均采用"默认运费"</span>
                                        )}
                                    </FormItem>
                                </Col>
                            </Form>
                            {/*自定义运费*/}
                            <Col offset={2} span={22}
                                 style={{display: this.state.currentPost == '0' ? 'block' : 'none'}}>
                                    <Col span={6}><Button onClick={() => {
                                        this.nextStep()
                                    }} type="primary">下一步</Button></Col>
                                    <Col span={6}> <Button onClick={() => {
                                        this.handleCancel()
                                    }} type="danger">取消</Button></Col>
                                </Col>

                            {/*卖家承担运费*/}
                            <Col offset={2} span={22}
                                 style={{display: this.state.currentPost == '1' ? 'block' : 'none'}}>
                                    <Col span={6}><Button loading={this.state.saveLoading} onClick={() => {
                                        this.handleSave()
                                    }} type="primary">保存并返回</Button></Col>
                                    <Col span={6}> <Button onClick={() => {
                                        this.handleCancel()
                                    }} type="danger">取消</Button></Col>
                                </Col>

                            <Col offset={1} span={23}>

                                      {/*给特定地区添加快递费的模板*/}
                                <AddDefultPosts
                                    loadingTwo={this.state.loadingTwo}
                                    getChildCancel={() => {
                                        this.handleCancel()
                                    }}

                                    currentPost={this.state.currentPost}
                                    getDefaultPost={(value, districtValue, districtCheck) => {
                                        this.handleGetDefaultPost(value, districtValue, districtCheck)
                                    }}
                                    childPrevStep={() => {
                                        this.getChildPrevStep()
                                    }}
                                    selectDeliverVisible={this.state.selectDeliverVisible}
                                    provinces={this.state.provinces}/>
                            </Col>
                        </Col>

                    </Row>

                </Row>
            </span>
        );
    }

    componentDidMount() {
        let formData = [];
        formData['template_shipping'] = {value: '1'};
        this.props.form.setFields(formData);
        // this.requestDistrict('', 'province');  //查看省

        this.handleSearchAllCity();
    }

    handleSearchAllCity() {
        app.post(china.SEARCH_ADDRESS_LIST, {}).then((body) => {
            if (body.code == 1) {
                this.setState({cityData: body.data});
            }
        })
    }

    // 获取子组件所有运费（子组件点击保存并返回按钮）传给服务器
    handleGetDefaultPost(para, districtValue, districtCheck) {
        let that = this;
        console.log(para, districtValue);
        let result;
        let temp;
        let count = 0;
        let districtDataList = districtValue;
        let districtData = [];  //指定地区的所有运费
        let isDistrictCheck = districtCheck;  //判断是否选择了指定地区
        let cityData = this.state.cityData;
        para.template_isArea = '2';
        this.props.form.validateFields((err, values) => {
            // 选择了指定地区
            if (isDistrictCheck) {
                para.template_isArea = '1';

                for (let h = 0; h < districtDataList.length; h++) {
                    let occurProvince = districtDataList[h].occurProvince;
                    for (let i = (occurProvince.length - 1); i >= 0; i--) {
                        for (let j = 0; j < cityData.length; j++) {
                            if (occurProvince[i] == cityData[j].id) {
                                occurProvince.splice(i, 1);
                                break;
                            } else {
                                for (let k = 0; k < cityData[j].sub.length; k++) {
                                    if (occurProvince[i] == cityData[j].sub[k].id) {
                                        occurProvince.splice(i, 1);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                districtDataList.forEach((item) => {
                    count = count + 1;
                    let id = '';
                    item.occurProvince.forEach((dataItem, indes) => {
                        id += dataItem + ',';
                    });

                    //循环得出区名字
                    let cityData = that.state.cityData;
                    let yetId = [];
                    let yetName = '';
                    cityData.map((p_item) => {
                        p_item.sub.map(c_item => {
                            c_item.sub.map(a_item => {
                                item.occurProvince.map(o_item => {
                                    if ((o_item == a_item.id) && (yetId.indexOf(o_item) == -1)) {
                                        yetId.push(o_item);
                                        yetName += a_item.name + ',';
                                    }
                                })
                            })
                        })
                    });
                    yetName = yetName.substring(0, yetName.length - 1);

                    id = id.substring(0, id.length - 1);
                    temp = {
                        template_area_content: id,
                        template_area_text: yetName,
                        template_area_firstNumber: item.first,
                        template_area_firstPrice: item.firstCost,
                        template_area_lastNumber: item.second,
                        template_area_lastPrice: item.secondCost,
                        template_area_key: count,  //供查询的时候根据这个来查找地区
                    };
                    districtData.push(temp);
                });

                para.areaList = JSON.stringify(districtData);  //所有指定地区的运费
            }


            if (!isDistrictCheck) {
                para.template_isArea = '0';  //没有指定地区
            }

            para.template_name = values.template_name;  //模板名称
            para.template_time = values.template_time;   //发货时间
            if (values.template_shipping === '0') {
                para.template_shipping = '2';//是否包邮(0,不包 1,包邮)
            } else {
                para.template_shipping = '1';//是否包邮(0,不包 1,包邮)
            }
            para.template_method = (Number(para.template_method) + 1).toString();
            para.template_type = (Number(para.template_type) + 1).toString();

            this.setState({
                loadingTwo: true
            });
            app.post(template.ADD_TEMPLATE, para).then(req => {
                that.setState({loading: false, loadingTwo: false});
                if (req.code === 1) {
                    app.alert('添加成功', 'success', 3);
                    this.props.history.push(path + '/home/transportTemplate'); //运费模板列表
                } else if (req.code == 2) {
                    app.alert(req.msg, 'error', 3)
                }
            })
        })
    }

    // 获取子组件的上一步按钮
    getChildPrevStep() {
        let formData = [];
        formData['template_shipping'] = {value: '0'};
        this.props.form.setFields(formData);

        this.setState({
            firstPage: 'block',
            selectDeliverVisible: 'none',　//选择运送方式
            currentPost: '0'  //隐藏第一页的所有按钮
        })
    }

    // 下一步
    nextStep() {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.setState({
                    firstPage: 'none',
                    selectDeliverVisible: 'block',　//选择运送方式
                    currentPost: '3'  //隐藏第一页的所有按钮
                })
            }
        })
    }

    // 判断是否包邮
    handleIsPost(e) {
        this.setState({
            currentPost: e.target.value
        })
    }

    // 省的值发生变化查找市
    handleSelectProvince(value) {
        let district = [];
        district['city'] = {value: ''};
        district['county'] = {value: ''};
        this.props.form.setFields(district);

        this.setState({
            citys: [],
            county: []
        })
        this.requestDistrict(value, 'city');
    }

    // 市的值发生变化查找区
    handleSelectCity(value) {
        let district = [];
        district['county'] = {value: ''};
        this.props.form.setFields(district);
        this.setState({
            county: []
        })
        this.requestDistrict(value, 'county');
    }

    // 请求省市区
    requestDistrict(pid, type) {
        let that = this;
        let districtList = [];
        let temp;
        app.post(requestUrl.SEARCH_DISTRICT, {pid: pid}).then(req => {
            let data = req.data;
            if (req.code === 1) {
                data.forEach((item) => {
                    temp = {
                        id: item.id,
                        name: item.name
                    }
                    districtList.push(temp);
                })

                // 查找省
                if (type == 'province') {
                    that.setState({
                        provinces: districtList
                    })
                }

                // 查找市
                if (type == 'city') {
                    that.setState({
                        citys: districtList
                    })
                }

                // 查找区
                if (type == 'county') {
                    that.setState({
                        countys: districtList
                    })
                }
                // app.alert(req.msg, 'info', 3);
            } else {
                // app.alert(req.msg, 'error', 3);
            }
        })
    }

    //第一页的点击保存并返回(我是卖家承担运费  免邮)
    handleSave() {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.setState({saveLoading: true, mySelftPost: true});
                app.post(template.ADD_TEMPLATE, values).then(req => {
                    this.setState({saveLoading: false});
                    if (req.code === 1) {
                        this.props.history.push(path + '/home/transportTemplate'); //运费模板列表
                        app.alert('添加成功', 'success', 3);
                    } else if (req.code == 2) {
                        app.alert(req.msg, 'error', 3)
                    }
                })
            }
        })
    };

    // 点击取消按钮
    handleCancel() {
        this.props.history.push(path + '/home/transportTemplate'); //运费模板列表
    }
}


// 设置默认运费
class AddDefultPost extends Component {
    constructor(props) {
        super(props);
        this.state = {
            addTransport: 'none',  //弹出为指定地区设置运费的内容
            costVisible: 'none',  //是否弹出默认运费
            first: '',
            addOrigin: '',
            costWayVisible: 'none',  //计价方式
            districtCheck: false,
            resetDistrictfields: false,  //是否清空为指定地区运费的提示语
            districtData: [],  //传给服务器的所有指定地区的运费
            firstPrecion: 0,  //按件数按体积按重量时首件和首体积手重量的小数位数不一样
            secondPrecion: 0,  //按件数按体积按重量时首件和首体积手重量的小数位数不一样
            clickPrev: false,   //判断是否点击了上一步，如果是则保持下一步的原样
            cityData: [],
        };
    }


    formItemLayout = {
        labelCol: {span: 4},
        wrapperCol: {span: 8},
    };
    formDistrictLayout = {
        labelCol: {span: 4},
        wrapperCol: {span: 20},
    };
    formTimeItemLayout = {
        labelCol: {span: 4},
        wrapperCol: {span: 17},
    };
    formPostAddLayout = {
        labelCol: {span: 8},
        wrapperCol: {span: 12},
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        return (
            <span>
                <Row>
                    <Col span={24} className='btnBottom'>
                        <Col span={24}>
                            <Form className="login-form">
                                {/*运送方式*/}
                                <FormItem style={{display: this.props.selectDeliverVisible}} label={"运送方式"}
                                          {...this.formItemLayout}>
                                    {getFieldDecorator('template_method', {
                                        rules: [{required: true, message: '请选择运送方式!'}],
                                    })(
                                        <RadioGroup onChange={(e) => {
                                            this.selectPsostWay(e)
                                        }}
                                                    style={{paddingTop: '0'}}
                                        >
                                            <Radio value={'0'}>快递</Radio>
                                            <Radio value={'1'}>EMS</Radio>
                                            <Radio value={'2'}>平邮</Radio>
                                        </RadioGroup>
                                    )}
                                </FormItem>

                                {/*根据运送方式选择计价方式*/}
                                <FormItem style={{backgroundColor: '#ddd', display: this.state.costWayVisible}}
                                          label={"请先选择计价方式"} {...this.formItemLayout}>
                                    {getFieldDecorator('template_type', {
                                        rules: [{required: true, message: '请选择计价方式!'}],
                                    })(
                                        <RadioGroup onChange={(e) => {
                                            this.selectCostWay(e)
                                        }}
                                                    style={{paddingTop: '0'}}
                                        >
                                            <Radio value={'0'}>按件数</Radio>
                                            <Radio value={'1'}>按重量</Radio>
                                            <Radio value={'2'}>按体积</Radio>
                                        </RadioGroup>
                                    )}
                                </FormItem>

                                {/*设置默认运费*/}
                                <Col span={24} style={{display: this.state.costVisible, border: '1px solid #ddd'}}
                                     className='btnBottom'>
                                    <Col offset={2} style={{fontSize: '16px', color: 'red'}}>默认运费</Col>
                                    <Col offset={2} span={22}>
                                        <Col span={10}>
                                            <FormItem label={this.state.first} {...this.formPostAddLayout}>
                                                {getFieldDecorator('template_firstNumber', {
                                                    rules: [{required: true, message: '请输入'}],
                                                })(
                                                    <InputNumber precision={this.state.firstPrecion} min={0}
                                                                 placeholder="请输入"/>
                                                )}
                                            </FormItem>

                                            <FormItem label={this.state.addOrigin} {...this.formPostAddLayout}>
                                                {getFieldDecorator('template_lastNumber', {
                                                    rules: [{
                                                        required: true,
                                                        message: '请输入'
                                                    }],
                                                })(
                                                    <InputNumber precision={this.state.secondPrecion} min={0}
                                                                 placeholder="请输入"/>
                                                )}
                                            </FormItem>
                                        </Col>

                                        <Col span={10}>
                                            <FormItem label={'首费'} {...this.formPostAddLayout}>
                                                {getFieldDecorator('template_firstPrice', {
                                                    rules: [{required: true, message: '请输入首费!'}],
                                                })(
                                                    <InputNumber min={0} precision={2} placeholder="请输入"/>
                                                )}
                                            </FormItem>

                                            <FormItem label={"续费(元)"} {...this.formPostAddLayout}>
                                                {getFieldDecorator('template_lastPrice', {
                                                    rules: [{required: true, message: '请输入续费!'}],
                                                })(
                                                    <InputNumber min={0} precision={2} placeholder="请输入"/>
                                                )}
                                            </FormItem>
                                        </Col>
                                    </Col>
                                </Col>

                            </Form>
                        </Col>

                        <Col span={24}>
                            <Col offset={2} style={{display: this.state.costVisible, color: 'black'}}>
                                <Col span={1}>选填</Col>
                                <Col>
                                    <Checkbox
                                        checked={this.state.districtCheck}
                                        onClick={(e) => {
                                            this.handelControlAdd(e)
                                        }} value={'1'}>为指定地区设置运费</Checkbox>
                                </Col>
                            </Col>
                            <DistrictPosts
                                first={this.state.first}
                                second={this.state.addOrigin}
                                firstPrecion={this.state.firstPrecion}
                                secondPrecion={this.state.secondPrecion}
                                getDistrictPost={(value) => {
                                    this.getChildDistrictPost(value)
                                }}
                                provinces={this.props.provinces}
                                resetDistrictfield={this.state.resetDistrictfields}
                                addTransport={this.state.addTransport}/>
                        </Col>
                    </Col>

                    <Col offset={2} span={22} style={{display: this.props.selectDeliverVisible}}>
                        <Button type='primary' onClick={() => {
                            this.prevStep()
                        }} className='btnRight'>上一步</Button>
                        <Button type='primary'
                                loading={this.props.loadingTwo}
                                className='btnRight' onClick={() => {
                            this.handleSaveTwo()
                        }}>保存并返回</Button>
                        <Button type='danger' onClick={() => {
                            this.handleTwoCancel()
                        }}>取消</Button>
                    </Col>
                </Row>
            </span>
        )

    }

    componentDidMount() {
        // this.handleSearchAllCity();
    }

    // handleSearchAllCity() {
    //     app.post(requestUrl.searchAddressList, {}).then((body) => {
    //         if (body.code == 1) {
    //             this.setState({cityData: body.data});
    //         }
    //     })
    // }

    componentWillReceiveProps(props) {
        if (this.state.clickPrev && (props.currentPost == '3')) {
            let xxx;
            this.setState({
                selectDeliverVisible: 'block',
                costWayVisible: 'block',
                costVisible: 'block',
                districtCheck: true, //复选框是否选中
                addTransport: 'block', //弹出为指定地区设置运费
                resetDistrictfields: false,
                clickPrev: false,
            })
        }
    }

    // 点击上一步
    prevStep() {
        this.props.childPrevStep();
        this.setState({
            costWayVisible: 'none',
            addTransport: 'none',
            costVisible: 'none',
            clickPrev: true, //判断是否点击了上一步，如果是则保持原样
        })
    }

    // 点击取消按钮
    handleTwoCancel() {
        this.props.getChildCancel()
    }

    // 第二页的保存并返回  把运送方式，计价方式，默认运费，指定地区的运费参数传给父组件
    handleSaveTwo() {
        let districtData = this.state.districtData;  //指定地区的运费
        let cityData = this.state.cityData;
        let indexArr = [];

        // districtData.occurProvince.forEach((itemNow,NowIndex)=>{
        //         cityData.forEach((itemPro,IndexPro)=>{
        //             if(itemPro.id == itemNow){
        //                 indexArr.push(NowIndex);
        //             }else{
        //                 itemPro.sub.forEach((itemCity,cityIndex)=>{
        //                     if(itemCity.id == itemNow){
        //                         indexArr.push(NowIndex);
        //                     }
        //                 })
        //             }
        //         })
        // });

        // for (let h = 0; h < districtData.length; h++)
        // {
        //     let occurProvince = districtData[h].occurProvince;
        //     for (let i = (occurProvince.length - 1); i >= 0; i--) {
        //         for (let j = 0; j < cityData.length; j++) {
        //             if (occurProvince[i] == cityData[j].id) {
        //                 occurProvince.splice(i, 1);
        //                 break;
        //             } else {
        //                 for (let k = 0; k < cityData[j].sub.length; k++) {
        //                     if (occurProvince[i] == cityData[j].sub[k].id) {
        //                         occurProvince.splice(i, 1);
        //                         break;
        //                     }
        //                 }
        //             }
        //         }
        //     }
        // }


        let districtCheck = this.state.districtCheck;//为指定地区设置运费是否选中
        this.props.form.validateFields((err, values) => {
            if (!err) {
                // 判断复选框是否选中
                if (districtCheck) {
                    if (districtData.length > 0) {
                        this.props.getDefaultPost(values, districtData, districtCheck);
                    } else {
                        message.info('您还没给指定地区设置运费！')
                    }
                } else {
                    this.props.getDefaultPost(values, districtData, districtCheck);
                }
            }
        })
    }


// 选择运送方式弹出计价方式
    selectPsostWay(e) {
        this.setState({
            costWayVisible: 'block',

        })
    }

// 获取子组件的为指定地区设置的运费
    getChildDistrictPost(value) {
        this.setState({
            districtData: value
        })
    }

// 点击计价方式(控制默认运费的显示文字)
    selectCostWay(e) {
        let type = e.target.value;
        let first = '';
        let addOrigin = '';
        let firstPrecion = 0;
        let secondPrecion = 0;
        //按件数
        if (type == '0') {
            first = '首件数（件）';
            addOrigin = '续件数（件）';
            firstPrecion = 0;
            secondPrecion = 0;
        }

        //按重量
        if (type == '1') {
            first = '首重（kg）';
            addOrigin = '续重量（kg）';
            firstPrecion = 3;
            secondPrecion = 3;
        }

        //按体积
        if (type == '2') {
            first = '首体积（m3）';
            addOrigin = '续体积（m3）';
            firstPrecion = 2;
            secondPrecion = 2;
        }

        this.setState({
            costVisible: 'block',
            first: first,
            addOrigin: addOrigin,
            firstPrecion: firstPrecion,  //按件数按体积按重量时首件和首体积手重量的小数位数不一样
            secondPrecion: secondPrecion,  //按件数按体积按重量时首件和首体积手重量的小数位数不一样
        })
    }

// 点击为指定地区设置默认运费的按钮
    handelControlAdd(e) {
        let districtCheck = this.state.districtCheck;
        let resetDistrictfields;

        // 选中状态
        if (districtCheck) {
            this.setState({
                districtData: []  //传给服务器的所有指定地区的运费
            })
            districtCheck = false;
            resetDistrictfields = false
        }

        // 取消选中
        else {
            districtCheck = true;
            resetDistrictfields = true
        }
        let addTransport = this.state.addTransport;
        let visible = '';
        if (addTransport == 'block') {
            visible = 'none';
        } else {
            visible = 'block'
        }

        this.setState({
            addTransport: visible,
            districtCheck: districtCheck,
            resetDistrictfields: resetDistrictfields
        })
    }

}


// 为指定地区设置运费
class DistrictPost extends Component {
    constructor(props) {
        super(props);
        this.state = {
            provinces: [],
            selectProvice: [],  //选中的省
            costModal: false,
            data: [],
            cityData: [],
            count: 0,
            options: [],
            pid: '',
        };
    }


    formItemLayout = {
        labelCol: {span: 4},
        wrapperCol: {span: 8},
    };
    formDistrictLayout = {
        labelCol: {span: 4},
        wrapperCol: {span: 20},
    };
    formTimeItemLayout = {
        labelCol: {span: 4},
        wrapperCol: {span: 17},
    };
    formPostAddLayout = {
        labelCol: {span: 8},
        wrapperCol: {span: 12},
    };

    render() {
        const {first, second, firstPrecion, secondPrecion} = this.props;
        const columns = [
            {
                title: '地区',
                dataIndex: this.columns,
                render: (data, text, index) => {
                    return (
                        <span>
                        <span className='btnRight'>{data.chineseName}...</span>

                        <SetDistrictCosts
                            cityData={this.state.cityData}  //传给子类的所有省市区
                            options={this.state.options}
                            data={data}
                            onOK={(value, editData, cityData) => {
                                this.getChildCost(value, editData, cityData)
                            }}

                        />
                    </span>
                    )
                }
            },
            {
                title: first,
                dataIndex: this.columns,
                render: (data, text, index) => {
                    return (
                        <InputNumber min={0} precision={firstPrecion} value={data.first} onChange={(e) => {
                            this.handleCHangeFirst(e, index)
                        }} type='text'/>
                    )
                }
            },
            {
                title: '首费',
                dataIndex: this.columns,
                render: (data, text, index) => {
                    return (
                        <InputNumber
                            min={0} precision={2}
                            onChange={(e) => {
                                this.handleCHangeFirstCost(e, index)
                            }}
                            value={data.firstCost}
                            type='text'/>
                    )
                }
            },
            {
                title: second,
                dataIndex: this.columns,
                render: (data, text, index) => {
                    return (
                        <InputNumber min={0} precision={secondPrecion} value={data.second}
                                     onChange={(e) => {
                                         this.handleCHangeSecond(e, index)
                                     }}
                                     type='text'/>
                    )
                }
            },
            {
                title: '续费',
                dataIndex: this.columns,
                render: (data, text, index) => {
                    return (
                        <InputNumber min={0} precision={2}
                                     onChange={(e) => {
                                         this.handleCHangeSecondCost(e, index)
                                     }}
                                     value={data.secondCost} type='text'/>
                    )
                }
            },
            {
                title: '操作',
                dataIndex: this.columns,
                render: (data, text, index) => {
                    return (
                        <span>
                       <Button type='danger' onClick={(datas, indexs) => {
                           this.deleteDistrictCost(data, index)
                       }}>删除</Button>
                    </span>
                    )
                }
            },
        ];
        return (
            <div>
                <Row style={{display: this.props.addTransport}}>
                    <Col span={24}>
                        <Form className="login-form">
                            <Col span={24} style={{border: '1px solid #ddd', padding: '20px 0px'}}>
                                <Col offset={4} span={20}>
                                    <Button type='primary' onClick={() => {
                                        this.setModalVisible(true)
                                    }}>添加</Button>

                                    <Table
                                        columns={columns}
                                        rowKey={record => record.id}
                                        dataSource={this.state.data}
                                    />
                                </Col>
                            </Col>
                        </Form>
                    </Col>


                </Row>
            </div>
        )

    }

    componentDidMount() {
        this.requestProvinces(); //查找所有的省
        this.handleSearchAllCity();
    }

    handleSearchAllCity() {
        app.post(china.SEARCH_ADDRESS_LIST, {}).then((body) => {
            if (body.code == 1) {
                this.setState({cityData: body.data || []});
            }
        })
    }

    // 获取首件数显示在文本框
    handleCHangeFirst = (value, index) => {
        let datasourse = this.state.data;
        datasourse[index].first = value;
        this.setState({
            data: datasourse
        })
    }

    // 获取首费用显示在文本框
    handleCHangeFirstCost = (value, index) => {
        let datasourse = this.state.data;
        datasourse[index].firstCost = value;
        this.setState({
            data: datasourse
        })
    }

    // 获取续件显示在文本框
    handleCHangeSecond = (value, index) => {
        let datasourse = this.state.data;
        datasourse[index].second = value;
        this.setState({
            data: datasourse
        })
    }

    // 获取续费显示在文本框
    handleCHangeSecondCost = (value, index) => {
        let datasourse = this.state.data;
        datasourse[index].secondCost = value;
        this.setState({
            data: datasourse
        })
    }

// 查找所有的省
    requestProvinces() {
        let temp;
        let options = [];
        app.post(requestUrl.SEARCH_DISTRICT, {pid: ''}).then(req => {
            let data = req.data;
            if (req.code === 1) {
                data.forEach((item) => {
                    temp = {
                        id: item.id,
                        label: item.name,
                        value: item.id + ',' + item.name,
                        disabled: false,
                    }
                    options.push(temp)
                })
                this.setState({
                    options: options || []
                })
                // app.alert(req.msg, 'info', 3);
            } else {
                // app.alert(req.msg, 'error', 3);
            }
        })
    }

    // 删除某个设置的地区
    deleteDistrictCost(deleteData, index) {
        const dataSource = [...this.state.data];
        let optionsReset = this.state.options;
        let selectProvince = deleteData.province;
        let result = selectProvince.indexOf(',');
        let compareProvince = [];
        let temp;
        if (deleteData.province != '请设置地区') {
            if (result > 0) {
                compareProvince = selectProvince.split(',');
            } else {
                // compareProvince = compareProvince.push(selectProvince);
                compareProvince.push(selectProvince);
            }
            optionsReset.forEach((provinceItem) => {
                compareProvince.forEach((selectItem) => {
                    if (provinceItem.label == selectItem) {
                        provinceItem.disabled = false;
                    }
                })
            })
        }

        this.setState({
            data: dataSource.filter(item => item.key !== deleteData.key),
            options: optionsReset
        });
    }


    // 设置是否弹出设置运费框
    setModalVisible() {
        const {count, data} = this.state;
        let tableData = this.state.data;
        let cityData = this.state.cityData;
        let flag = 0;
        if (tableData.length == 0) {
            const newData = {
                id: count,
                key: count,
                province: `请设置地区`,
                first: 0,
                firstCost: 0,
                second: 0,
                secondCost: 0,
                chineseName: '',
                occurProvince: []
            };
            this.setState({
                data: [...data, newData],
                count: count + 1,
            });
        } else {
            tableData.forEach((item) => {
                if (item.province == '请设置地区') {
                    flag = 1;
                    message.info('请选择地区');
                    return false;
                }
            })

            if (flag == 0) {
                const newData = {
                    id: count,
                    key: count,
                    province: `请设置地区`,
                    first: 0,
                    firstCost: 0,
                    second: 0,
                    secondCost: 0,
                    chineseName: '',
                    occurProvince: []
                };
                this.setState({
                    data: [...data, newData],
                    count: count + 1,
                });
            }
        }
    }


    // 获取子组件选中的地区并显示在表格中
    getChildCost(value, editData, cityData) {
        const _this = this;
        let data = this.state.data;
        let temp = '';
        let options = this.state.options;
        let citysdata = value.cityData;
        let requestData = editData;
        // citysdata.forEach((DistrictItem, indexs) => {
        //     //对比看是不是区的id，不是的剔除，是的保留转成字符串以逗号隔开
        //
        //     _this.state.cityData.forEach((itemProvince, indexProvince) => {
        //         if (DistrictItem.id == itemProvince.id) {
        //             citysdata.splice(indexs, 1);
        //         }
        //         itemProvince.sub.forEach((itemCity, indexCity) => {
        //             if (DistrictItem == itemCity.id) {
        //                 citysdata.splice(indexs, 1);
        //             }
        //         })
        //
        //     })
        //
        //
        // });
        citysdata.forEach((item, index) => {
            temp += item + ',';
        });
        temp.substring(0, temp.length - 1);

        console.log(temp)
        // temp = temp.substring(0, temp.length - 1);
        requestData.province = temp;
        let items;
        requestData.occurProvince = value.specialDistrict;

        data.forEach((item) => {
            if (item.id == requestData.id) {
                items = requestData
            }
        })

        let length;
        if (data.length == 0) {
            length = data.length;
        } else {
            length = data.length - 1;
        }
        this.state.data[length].province = citysdata[length];
        let chineseName = '';

        this.state.cityData.forEach((item, index) => {
            if (item.id == citysdata[length]) {
                chineseName = item.name;
            } else {
                item.sub.map((items, indexs) => {
                    if (items.id == citysdata[length]) {
                        chineseName = items.name;
                    } else {
                        items.sub.map((itemz, indexz) => {
                            if (itemz.id == citysdata[length]) {
                                chineseName = itemz.name;
                            }
                        })
                    }
                })
            }
        })

        this.state.data[editData.id].chineseName = chineseName;

        this.state.data[editData.id].occurProvince = citysdata;
        this.setState({
            data,
            cityData
        })

        this.props.getDistrictPost(data); //把指定地区设置运费的值传给父组件
    }

    componentWillReceiveProps(preops) {
        let that = this;
        let optionsReset = this.state.options;
        if (!preops.resetDistrictfield) {
            this.props.form.resetFields();
        }

        // 如果没有选中为指定地区设置运费，则把表格数据清空
        if (preops.addTransport == 'none') {
            optionsReset.forEach((provinceItem) => {
                provinceItem.disabled = false;
            })
            this.setState({
                // data: [],
                options: optionsReset
            })
        }
    }

}


// 地区添加弹出框
class SetDistrictCost extends Component {
    constructor(props) {
        super(props);
        this.state = {
            districtOptions: this.props.options, //所有的省
            visible: false,
            editData: [],  //选中的地区
            province: [],
            city: [],
            area: [],
            allId: [],
            cityData: this.props.cityData,

        };
    }

    formItemLayout = {
        labelCol: {span: 8},
        wrapperCol: {span: 12},
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        return (
            <span>
                      <Icon
                          className="editIcon"
                          type="edit"
                          style={{fontSize: '18px', color: 'red'}}
                          onClick={() => {
                              this.handleCancel(true)
                          }}
                      />
                     <Modal
                         data={this.props.data}
                         maskClosable={false}
                         title={'为指定地区设置运费'}
                         wrapClassName="vertical-center-modal"
                         width={'600px'}
                         onOk={() => {
                             this.handleSubmit()
                         }}
                         visible={this.state.visible}
                         onCancel={() => {
                             this.handleCancel(false)
                         }}
                     >
                         <Row style={{height: '800px', overflow: 'scroll'}}>
                               <Col offset={1} span={23}>
                                   <Form>
                                        {/*<FormItem label={"选择地区"} {...this.formDistrictLayout}>*/}
                                       {/*{*/}
                                       {/*this.state.province.map((item, index) => {*/}
                                       {/*if (!item.sublist) {*/}
                                       {/*item.sublist = [];*/}
                                       {/*}*/}
                                       {/*return (*/}
                                       {/*<Tree key={item.id}*/}
                                       {/*checkable*/}
                                       {/*onSelect={this.onSelect}*/}
                                       {/*onCheck={this.onCheck}*/}
                                       {/*>*/}
                                       {/*<TreeNode key={item.id} title={item.name} >*/}
                                       {/*{*/}
                                       {/*item.sublist.map((items, indes) => {*/}
                                       {/*if (!items.sublist) {*/}
                                       {/*items.sublist = [];*/}
                                       {/*}*/}

                                       {/*return (*/}
                                       {/*<TreeNode title={items.name} key={items.id}>*/}
                                       {/*{*/}
                                       {/*items.sub.map((itemz,indez)=>{*/}
                                       {/*if (!itemz.sublist) {*/}
                                       {/*itemz.sublist = [];*/}
                                       {/*}*/}
                                       {/*return(*/}
                                       {/*<TreeNode title={<span*/}
                                       {/*style={{color: '#1890ff'}}>{itemz.name}</span>}*/}
                                       {/*key={itemz.id}/>*/}
                                       {/*)*/}
                                       {/*})*/}
                                       {/*}*/}

                                       {/*</TreeNode>*/}
                                       {/*)*/}
                                       {/*})*/}
                                       {/*}*/}
                                       {/*</TreeNode>*/}
                                       {/*</Tree>*/}
                                       {/*)*/}
                                       {/*})*/}

                                       {/*}*/}

                                       {/*</FormItem>*/}


                                       <FormItem label={"选择地区"} {...this.formDistrictLayout}>

                                                        <Tree
                                                            checkable
                                                            onSelect={this.onSelect}
                                                            onCheck={this.onCheck}

                                                        >
                                                            {
                                                                this.state.cityData.map((item, index) => {
                                                                    return (
                                                                        <TreeNode disabled={item.disabled}
                                                                                  title={item.name} key={item.id}>
                                                                            {
                                                                                item.sub.map((itemCity, indexCity) => {
                                                                                    return (
                                                                                        <TreeNode
                                                                                            disabled={itemCity.disabled}
                                                                                            title={itemCity.name}
                                                                                            key={itemCity.id}>
                                                                                            {
                                                                                                itemCity.sub.map((itemArea, indexArea) => {
                                                                                                    return (
                                                                                                        <TreeNode
                                                                                                            disabled={itemArea.disabled}
                                                                                                            title={itemArea.name}
                                                                                                            key={itemArea.id}/>
                                                                                                    )
                                                                                                })
                                                                                            }
                                                                                        </TreeNode>
                                                                                    )
                                                                                })
                                                                            }
                                                                        </TreeNode>

                                                                    )
                                                                })
                                                            }
                                                        </Tree>


                                        </FormItem>

                                   </Form>
                               </Col>
                         </Row>

                </Modal>
            </span>
        )

    }

    componentDidMount() {
        // this.handleSearchAllCity();
    }

    // handleSearchAllCity() {
    //     app.post(requestUrl.searchAddressList, {}).then((body) => {
    //         if (body.code == 1) {
    //             this.setState({cityData: body.data || []});
    //         }
    //     })
    // }

    /*查出所有的省*/
    handleSearchAllProvince() {
        return app.post(requestUrl.SEARCH_DISTRICT, {token: app.getToken()}).then((req) => {
            if (req.code === 1) {
                this.setState({province: req.data});
            }
        })
    }


    onSelect = (selectedKeys, info) => {
        console.log('selected', selectedKeys, info);
        let provin = this.state.province;
        let flag = false;
        let pid = '';
        provin.forEach((item, index) => {
            if (item.id == selectedKeys) {
                flag = true;
            }
        });
        if (flag == true) {
            pid = provin.findIndex(function (item) {
                return item.id == selectedKeys
            });
            console.log(pid);
            app.post(requestUrl.searchAllAddress, {token: app.getToken(), pid: selectedKeys[0]}).then((req) => {
                let province = this.state.province;

                if (req.code === 1) {
                    province[pid].sublist = req.data.sub;
                    this.state.pid = pid;
                    this.setState({province});
                    console.log(this.state.province);
                }
            });
        }


    }
    // let provin = this.state.province;
    // let flag = false;
    // let pid = '';
    // provin.forEach((item,index)=>{
    //    if(item.id == selectedKeys){
    //        flag = true;
    //    }
    // });
    // if(flag == true){
    //     pid = provin.findIndex(function (item) {
    //         return item.id == selectedKeys
    //     });
    //     console.log(pid);
    //     app.post(requestUrl.searchAllAddress, {token: app.getToken(), pid: selectedKeys[0]}).then((req) => {
    //         let province = this.state.province;
    //         province[pid].sublist = req.data;
    //         if (req.code ===  1) {
    //             this.state.pid = pid;
    //             this.setState({province});
    //         }
    //     });
    // }else{
    //     let pids = provin[this.state.pid].sublist;
    //     pid = pids.findIndex(function (items) {
    //         return items.id == selectedKeys
    //     });
    //     console.log(pid);
    //     app.post(requestUrl.SEARCH_DISTRICT, {token: app.getToken(), pid: selectedKeys[0]}).then((req) => {
    //         let province = this.state.province;
    //         province[this.state.pid].sublist[pid].sublist = req.data;
    //         // pids[pid].sublist = req.data;
    //         if (req.code ===  1) {
    //             // this.state.pid = pid;
    //             this.setState({province});
    //         }
    //     });
    // }

    // onCheck = (checkedKeys, info) => {
    //     const _this = this;
    //     console.log('onCheck', checkedKeys, info);
    //     let allId = _this.state.allId;
    //     let newID = [];
    //     let array = [];
    //     if(allId.length == 0){
    //         _this.state.allId = checkedKeys;
    //     }else{
    //         for(let i in allId){
    //             if(allId.indexOf(checkedKeys[i]) == -1 ){
    //                 if(checkedKeys[i]){
    //                     newID.push(checkedKeys[i]);
    //                 }
    //             }
    //         }
    //         array = allId.concat(newID);
    //         _this.state.allId = array;
    //     }
    //
    //     console.log(_this.state.allId);
    //
    //
    // }

    /*新的check方法*/
    onCheck = (checkedKeys, info) => {
        const _this = this;
        console.log('onCheck', checkedKeys, info);
        _this.state.allId = checkedKeys;
        console.log(_this.state.allId);
    }

    // 获取选中的地区
    onChangeDistrict(value) {
        this.setState({
            selectProvice: value
        })
    }

// 点击弹出框的确定按钮
    handleSubmit() {
        this.props.form.validateFields((err, values) => {
            values.cityData = this.state.allId;
            if (!err) {
                let cityData = this.props.cityData;
                cityData.forEach((itemid, itemindex) => {
                    values.cityData.forEach((cityDataId, ItemIndexId) => {
                        if (itemid.id == cityDataId) {
                            itemid.disabled = true;
                        } else {
                            itemid.sub.forEach((itemCity, ItemIndex) => {
                                if (itemCity.id == cityDataId) {
                                    itemCity.disabled = true;
                                } else {
                                    itemCity.sub.forEach((itemArea, AreaIndex) => {
                                        if (itemArea.id == cityDataId) {
                                            itemArea.disabled = true;
                                        } else {
                                        }
                                    })
                                }
                            })
                        }
                    })
                });
                // this.state.cityData = cityData;
                this.props.onOK(values, this.state.editData, cityData);
                console.log(this.state.editData);
                this.props.form.resetFields();
                this.setState({
                    visible: false,
                })
            }
        })
    }

    // 弹出框的打开与关闭
    handleCancel(visible) {
        let data = this.props.data;
        let districtOptions = this.props.cityData;

        if (visible) {
            districtOptions.forEach((OptionsItem, OptionsIndex) => {
                data.occurProvince.forEach((itemPro, dataindex) => {
                    if (itemPro == OptionsItem.id) {
                        OptionsItem.disabled = false;
                    } else {
                        OptionsItem.sub.forEach((OpCity, Opindex) => {
                            if (itemPro == OpCity.id) {
                                OpCity.disabled = false;
                            } else {
                                OpCity.sub.forEach((OpArea, OpAIndex) => {
                                    if (itemPro == OpArea.id) {
                                        OpArea.disabled = false;
                                    }
                                })
                            }
                        })
                    }
                })
            })
        } else {
            districtOptions.forEach((OptionsItem, OptionsIndex) => {
                data.occurProvince.forEach((itemPro, dataindex) => {
                    if (itemPro == OptionsItem.id) {
                        OptionsItem.disabled = true;
                    } else {
                        OptionsItem.sub.forEach((OpCity, Opindex) => {
                            if (itemPro == OpCity.id) {
                                OpCity.disabled = true;
                            } else {
                                OpCity.sub.forEach((OpArea, OpAIndex) => {
                                    if (itemPro == OpArea.id) {
                                        OpArea.disabled = true;
                                    }
                                })
                            }
                        })
                    }
                })
            })
        }


        console.log(districtOptions);

        let result = data.province.search(',');  //判断是否只选择了一个地区
        let isTrue;  //关闭时禁止复选框，弹出时可选复选框


        if (visible) {
            isTrue = false;
        }
        if (!visible) {
            isTrue = true
        }

        //已经有的地区在复选框中勾选
        let formData = [];
        formData['specialDistrict'] = {value: data.occurProvince};
        this.props.form.setFields(formData);

        // // 控制复选框中除该行选中的地区之外的选中地区禁止掉
        // districtOptions.forEach((provinceItem, index) => {
        //     if (data.province != '请设置地区') {
        //         if (result > 0) {
        //             (data.province.split(',')).forEach((dataItem) => {
        //                 if (dataItem == provinceItem.label) {
        //                     provinceItem.disabled = isTrue
        //                 }
        //             })
        //         }
        //         else {
        //             if (data.province == provinceItem.label) {
        //                 provinceItem.disabled = isTrue
        //             }
        //         }
        //     }
        //
        // })

        this.setState({
            editData: data,
            visible: visible,
            // districtOptions: districtOptions
        })
    }


}

const SetDistrictCosts = Form.create()(SetDistrictCost);


const DistrictPosts = Form.create()(DistrictPost);
const AddDefultPosts = Form.create()(AddDefultPost);
const AddTransports = Form.create()(AddTransport);
export default AddTransports;